﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Metro.Kashikoi.Common
{
    /// <summary>
    /// Reflection utility.
    /// </summary>
    public static class ReflectionUtil
    {
        /// <summary>
        /// Sets the property.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <param name="name">The name.</param>
        /// <param name="value">The value.</param>
        public static void SetProperty(object obj, string name, object value)
        {
            PropertyInfo prop = obj.GetType().GetProperty(name,
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            if (null != prop && prop.CanWrite)
            {
                prop.SetValue(obj, value, null);
            }
        }

        /// <summary>
        /// Creates an instance of the specified type using that type's default constructor.
        /// </summary>
        /// <param name="type">The type of object to create.</param>
        /// <param name="args">The args.</param>
        /// <returns>
        /// A reference to the newly created object.
        /// </returns>
        public static T CreateInstance<T>(Type type, params object[] args) where T : class
        {
            return Activator.CreateInstance(type, args) as T;
        }

        /// <summary>
        /// Creates an instance of the type whose name is specified, using the named
        /// assembly and default constructor.
        /// </summary>
        /// <param name="type">The name of the preferred type.</param>
        /// <param name="args">The args.</param>
        /// <returns>
        /// The newly created instance.
        /// </returns>
        public static T CreateInstance<T>(string type, params object[] args) where T : class
        { 
            return CreateInstance<T>(Type.GetType(type), args);
        }
    }
}
